import React, { useState, useEffect, useRef } from 'react';
import {
 Typography,
 Box,
 Card,
 CardContent,
 Avatar,
 Button,
 TextField,
 Dialog,
 DialogTitle,
 DialogContent,
 DialogActions,
 Snackbar,
 Alert,
 CircularProgress,
 Chip,
 Divider,
 IconButton,
} from '@mui/material';
import {
 Person,
 Email,
 Edit,
 Camera,
 Save,
 Cancel,
 CalendarToday,
 Badge,
} from '@mui/icons-material';
import { useUser } from '../../hooks/useUser';
import { User } from '../../types';
import { userStorage } from '../../utils/api';

const Profile: React.FC = () => {
 const { loading, error, getCurrentUser, updateUserProfile } = useUser();
 const [user, setUser] = useState<User | null>(null);
 const [editDialogOpen, setEditDialogOpen] = useState(false);
 const [snackbar, setSnackbar] = useState({
   open: false,
   message: '',
   severity: 'success' as 'success' | 'error' | 'info' | 'warning',
 });

 // 编辑表单状态
 const [editForm, setEditForm] = useState({
   username: '',
   bio: '',
   avatar: null as File | null,
 });
 const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
 const [updateLoading, setUpdateLoading] = useState(false);
 const fileInputRef = useRef<HTMLInputElement>(null);

 // 加载用户信息
 useEffect(() => {
   const loadUserInfo = async () => {
     try {
       // 先从本地存储获取
       const localUser = userStorage.get();
       if (localUser) {
         setUser(localUser);
       }

       // 从服务器获取最新信息
       const userData = await getCurrentUser();
       setUser(userData);
     } catch (err) {
       console.error('获取用户信息失败:', err);
       setSnackbar({
         open: true,
         message: '获取用户信息失败',
         severity: 'error',
       });
     }
   };

   loadUserInfo();
 }, [getCurrentUser]);

 // 打开编辑对话框
 const handleEditClick = () => {
   if (user) {
     setEditForm({
       username: user.username || '',
       bio: user.bio || '',
       avatar: null,
     });
     setAvatarPreview(null);
     setEditDialogOpen(true);
   }
 };

 // 关闭编辑对话框
 const handleEditClose = () => {
   setEditDialogOpen(false);
   setEditForm({
     username: '',
     bio: '',
     avatar: null,
   });
   setAvatarPreview(null);
 };

 // 处理头像选择
 const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
   const file = event.target.files?.[0];
   if (file) {
     // 检查文件类型
     if (!file.type.startsWith('image/')) {
       setSnackbar({
         open: true,
         message: '请选择图片文件',
         severity: 'error',
       });
       return;
     }

     // 检查文件大小（5MB）
     if (file.size > 5 * 1024 * 1024) {
       setSnackbar({
         open: true,
         message: '图片大小不能超过5MB',
         severity: 'error',
       });
       return;
     }

     setEditForm(prev => ({ ...prev, avatar: file }));

     // 创建预览
     const reader = new FileReader();
     reader.onload = (e) => {
       setAvatarPreview(e.target?.result as string);
     };
     reader.readAsDataURL(file);
   }
 };

 // 提交更新
 const handleUpdate = async () => {
   if (!editForm.username.trim()) {
     setSnackbar({
       open: true,
       message: '用户名不能为空',
       severity: 'error',
     });
     return;
   }

   setUpdateLoading(true);
   try {
     const updateData = {
       username: editForm.username.trim(),
       bio: editForm.bio.trim(),
       ...(editForm.avatar && { avatar: editForm.avatar }),
     };

     const updatedUser = await updateUserProfile(updateData);
     setUser(updatedUser);
     setEditDialogOpen(false);
     setSnackbar({
       open: true,
       message: '个人信息更新成功',
       severity: 'success',
     });
   } catch (err) {
     setSnackbar({
       open: true,
       message: '更新失败，请稍后重试',
       severity: 'error',
     });
   } finally {
     setUpdateLoading(false);
   }
 };

 // 关闭提示
 const handleCloseSnackbar = () => {
   setSnackbar(prev => ({ ...prev, open: false }));
 };

 // 格式化日期
 const formatDate = (dateString: string) => {
   return new Date(dateString).toLocaleDateString('zh-CN', {
     year: 'numeric',
     month: 'long',
     day: 'numeric',
   });
 };

 // 获取角色显示文本
 const getRoleText = (role: string) => {
   switch (role) {
     case 'ADMIN':
       return '管理员';
     case 'SUPERADMIN':
       return '超级管理员';
     default:
       return '普通用户';
   }
 };

 // 获取角色颜色
 const getRoleColor = (role: string) => {
   switch (role) {
     case 'ADMIN':
       return 'primary';
     case 'SUPERADMIN':
       return 'error';
     default:
       return 'default';
   }
 };

 if (loading && !user) {
   return (
     <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
       <CircularProgress />
     </Box>
   );
 }

 if (error && !user) {
   return (
     <Box sx={{ textAlign: 'center', py: 4 }}>
       <Typography color="error">{error}</Typography>
       <Button onClick={() => window.location.reload()} sx={{ mt: 2 }}>
         重新加载
       </Button>
     </Box>
   );
 }

 return (
   <Box sx={{ maxWidth: 800, mx: 'auto', p: 3 }}>
     {/* 页面标题 */}
     <Typography variant="h4" component="h1" gutterBottom sx={{ mb: 4 }}>
       个人资料
     </Typography>

     {user && (
       <Card>
         <CardContent sx={{ p: 4 }}>
           <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
             <Avatar
               src={user.avatar}
               sx={{ width: 100, height: 100, mr: 3 }}
             >
               {user.username?.[0]?.toUpperCase() || <Person sx={{ fontSize: 50 }} />}
             </Avatar>
             <Box sx={{ flexGrow: 1 }}>
               <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
                 <Typography variant="h5">
                   {user.username || '未设置用户名'}
                 </Typography>
                 <Chip
                   label={getRoleText(user.role)}
                   color={getRoleColor(user.role) as any}
                   size="small"
                   icon={<Badge />}
                 />
               </Box>
               <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                 {user.bio || '这个人很懒，什么都没有留下...'}
               </Typography>
               <Button
                 variant="contained"
                 startIcon={<Edit />}
                 onClick={handleEditClick}
                 size="small"
               >
                 编辑资料
               </Button>
             </Box>
           </Box>

           <Divider sx={{ my: 3 }} />

           <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
             <Email sx={{ mr: 2, color: 'text.secondary' }} />
             <Box>
               <Typography variant="subtitle2">邮箱地址</Typography>
               <Typography variant="body2" color="text.secondary">
                 {user.email}
               </Typography>
             </Box>
           </Box>

           <Box sx={{ display: 'flex', alignItems: 'center' }}>
             <CalendarToday sx={{ mr: 2, color: 'text.secondary' }} />
             <Box>
               <Typography variant="subtitle2">注册时间</Typography>
               <Typography variant="body2" color="text.secondary">
                 {formatDate(user.createdAt)}
               </Typography>
             </Box>
           </Box>
         </CardContent>
       </Card>
     )}

     {/* 编辑对话框 */}
     <Dialog open={editDialogOpen} onClose={handleEditClose} maxWidth="sm" fullWidth>
       <DialogTitle>编辑个人资料</DialogTitle>
       <DialogContent>
         {/* 头像编辑 */}
         <Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
           <Box sx={{ position: 'relative' }}>
             <Avatar
               src={avatarPreview || user?.avatar}
               sx={{ width: 120, height: 120 }}
             >
               {user?.username?.[0]?.toUpperCase() || <Person sx={{ fontSize: 60 }} />}
             </Avatar>
             <IconButton
               sx={{
                 position: 'absolute',
                 bottom: 0,
                 right: 0,
                 backgroundColor: 'primary.main',
                 color: 'white',
                 '&:hover': {
                   backgroundColor: 'primary.dark',
                 },
               }}
               size="small"
               onClick={() => fileInputRef.current?.click()}
             >
               <Camera />
             </IconButton>
             <input
               ref={fileInputRef}
               type="file"
               accept="image/*"
               style={{ display: 'none' }}
               onChange={handleAvatarChange}
             />
           </Box>
         </Box>

         {/* 用户名 */}
         <TextField
           fullWidth
           label="用户名"
           value={editForm.username}
           onChange={(e) => setEditForm(prev => ({ ...prev, username: e.target.value }))}
           margin="normal"
           required
           helperText="用户名长度为2-20个字符"
         />

         {/* 个人简介 */}
         <TextField
           fullWidth
           label="个人简介"
           value={editForm.bio}
           onChange={(e) => setEditForm(prev => ({ ...prev, bio: e.target.value }))}
           margin="normal"
           multiline
           rows={3}
           helperText="简单介绍一下自己吧"
         />
       </DialogContent>
       <DialogActions>
         <Button onClick={handleEditClose} startIcon={<Cancel />}>
           取消
         </Button>
         <Button
           onClick={handleUpdate}
           variant="contained"
           startIcon={<Save />}
           disabled={updateLoading}
         >
           {updateLoading ? <CircularProgress size={20} /> : '保存'}
         </Button>
       </DialogActions>
     </Dialog>

     {/* 提示信息 */}
     <Snackbar
       open={snackbar.open}
       autoHideDuration={3000}
       onClose={handleCloseSnackbar}
       anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
     >
       <Alert onClose={handleCloseSnackbar} severity={snackbar.severity}>
         {snackbar.message}
       </Alert>
     </Snackbar>
   </Box>
 );
};

export default Profile;